<?php

/*
 *
 *
 * This software has been made FREELY available by author for interest of the developers. 
 *      I hope this will help you in coding faster and robust php application
 *            You can modify and use it as you it suits you.
 *              Your comments, suggestions and corrections 
 *                          will be highly 
 *                           APPRECIATED. 
 *                                      Thanks, 
 *                                      Author
 * @author :   Roshan Budhathoki (contact@roshanbudhathoki.com);
 * @URL    :   <http://www.roshanbudhathoki.com>
 *
 */

/*
 * *****************************************************************
 * CLASS AUTOLOADER. INVOKED WHEN CLASS IS USED WITHTOUT DEFINITION
 * *****************************************************************
 */

function autoload($class) {
	$class = trim ( strtolower ( $class ) ) . '.php';
	// CHECK IN CORE 
	if (file_exists ( core_path () . $class )) {
		require_once core_path () . $class;
		/* } else if (file_exists ( model_path () . $class )) {
		require_once model_path () . $class; */
	} else {
		
		$parts = explode ( '_', $class );
		$name = implode ( DS, $parts );
		
		if (file_exists ( app_path () . $name )) {
			require_once app_path () . $name;
		
		// LOOK IN EXTERNAL LIBRARAY
		} else {
			$parts = explode ( '_', $class );
			foreach ( $parts as $key => $part ) {
				$parts [$key] = ucfirst ( strtolower ( $part ) );
			}
			$last = implode ( DS, $parts );
			$last = lib_path () . $last;
			
			if (file_exists ( $last )) {
				require_once $last;
			}
		}
	
	}

}

/*
 * *******************************************
 * URL REDIRECTION
 * *******************************************
 */

function redirect($page) {
	if ($page == '') {
		return false;
	}
	
	if (strpos ( $page, 'www' )) {
		header ( 'Location:' . $page );
	} else {
		header ( 'Location:' . site_url () . $page );
	}
}

/*
 * ***************************************************
 * CLEAN SUPERGLOBAL ARRAYS TO PREVENT GLOBAL HACK
 * ***************************************************
 */

function unregister_globals() {
	if (! ini_get ( 'register_globals' ))
		return;
	
	if (isset ( $_REQUEST ['GLOBALS'] ))
		die ( 'GLOBALS overwrite attempt detected' );
	
		// Variables that shouldn't be unset
	$no_unset = array ('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES', 'table_prefix' );
	
	$input = array_merge ( $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset ( $_SESSION ) && is_array ( $_SESSION ) ? $_SESSION : array () );
	foreach ( $input as $k => $v )
		if (! in_array ( $k, $no_unset ) && isset ( $GLOBALS [$k] )) {
			$GLOBALS [$k] = null;
			unset ( $GLOBALS [$k] );
		}
}

/*
 * ***************************************
 * Checks whether user is logged in or not
 * ***************************************
 */

function user_logged_in() {
	if (Session::newInstance ()->_get ( 'current_user' )) {
		return true;
	} else {
		return false;
	}
	/*
	if (isset ( $_SESSION ['current_user'] )) {
		if ($_SESSION ['current_user']) {
			return true;
		}
	}
	return false;
	*/
}

/*
 * *************************************
 * Strips slasses of the given array
 * *************************************
 */

function strip_slashes_extended($array) {
	if (is_array ( $array )) {
		foreach ( $array as $k => &$v ) {
			$v = strip_slashes_extended ( $v );
		}
	} else {
		$array = stripslashes ( $array );
	}
	return $array;
}

/*
 * **************************************
 * Retrieves Site URL
 * **************************************
 */

function site_url($https = false) {
	
	if ($https) {
		$protocol = 'https://';
		return str_replace ( 'http://', 'https://', SITE_URL );
	}
	return SITE_URL;
}

/*
 * **********************************
 * Retrieves Current URL
 * **********************************
 */

function current_uri() {
	$url = $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
	$str = array ();
	
	foreach ( $_GET as $key => $value ) {
		$str [$key] = $key . '=' . $value;
	}
	unset ( $str ['page'] );
	unset ( $str ['action'] );
	if ($str) {
		$url = $url . '?' . implode ( '&', $str );
	}
	$url = str_replace ( 'http://', '', $url );
	$url = 'http://' . $url;
	
	return $url;
}

/*
 * ****************************
 * REDIRECTS HTTP TO HTTPS
 * ****************************
 */

function ssl_redirect($url) {
	$url = str_replace ( 'http', 'https', $url );
	redirect ( $url );

}

/*
 * ****************************
 * Returns site Path
 * ****************************
 */

function site_root() {
	return APP_ROOT;
}

/*
 * ********************************
 * Site Application Path
 * ********************************
 */
function app_path() {
	return APP_PATH;
}

/*
 * *********************************
 * Returns Content URL
 * *********************************
 */

function content_url() {
	return site_url () . 'content/frontend/';
}

/*
 * ***************************************
 * Returns path for the content folder
 * ***************************************
 */

function content_path() {
	return APP_ROOT . 'content' . DS . 'frontend' . DS;
}

/*
 * *****************************
 * Returns code path
 * *****************************
 */
function code_path() {
	return APP_PATH . 'code' . DS;
}

/*
 * ********************************
 * Retrieves Model Path
 * ********************************
 */

function model_path() {
	return APP_PATH . 'model' . DS;
}

/*
 * ***********************************
 * Retrieves Core Path
 * ***********************************
 */
function core_path() {
	return APP_PATH . 'core' . DS;
}

/*
 * *********************************
 * Retrieves Template path
 * *********************************
 */

function template_path() {
	return APP_PATH . 'templates' . DS;
}

/*
 * **********************************
 * Returns Admin path
 * **********************************
 */

function cp_path() {
	return app_path () . ADMIN . DS;
}

/*
 * ******************************************************
 * RETURNS LIB PATH WHERE EXTERNAL LIBRARIES ARE SOTRED
 * ******************************************************
 */

function lib_path() {
	return app_path () . 'lib' . DS;
}

/*
 * **********************
 * RETURNS PLUGIN PATH
 * **********************
 */

function plugin_path() {
	return app_path () . 'plugins' . DS;
}

/*
 * *******************************
 * Returns site admin url
 * *******************************
 */
function cp_url() {
	return site_url () . ADMIN . '/';
}

/*
 * ****************************
 * Retrieves CP content path
 * ****************************
 */

function cp_content_path() {
	return APP_ROOT . 'content' . DS . 'admin' . DS;
}

/*
 * ***********************************
 * Retrieves templates path of admin
 * ***********************************
 */

function cp_template_path() {
	return cp_path () . 'templates' . DS;
}

/*
 * **************************
 * Retrives Admin Code Path
 * *************************
 */

function cp_code_path() {
	return cp_path () . 'code' . DS;
}

/*
 * *************************************
 * Retrieves Content URL of Admin
 * *************************************
 */

function cp_content_url() {
	return site_url () . 'content/admin/';
}

/*
 * **********************************************************************
 * Retrieves Path for cache folder and creates one if it does not exists
 * **********************************************************************
 */

function cache_path() {
	if (is_dir ( APP_ROOT . 'cache' . DS )) {
		return APP_ROOT . 'cache' . DS;
	} else {
		if (mkdir ( APP_ROOT . 'cache' . DS, 0755 )) {
			return APP_ROOT . 'cache' . DS;
		} else {
			throw new Exception ( 'Cache folder could not be created' );
		}
	}

}

/*
 * ********************************************
 * CREATES OPTIONS BASED ON PROVIDED ARRAY
 * ********************************************
 */

function create_options($args, $key, $value, $prefix = '', $selected = '') {
	if (! is_array ( $args ) || $key == '' || $value == '') {
		return false;
	}
	//print_r($args);
	foreach ( $args as $i => $item ) {
		if ($selected == '') {
			echo '<option value="' . $item [$key] . '" >' . $prefix . $item [$value] . '</option>';
		} else {
			if ($selected == $item [$key]) {
				echo '<option value="' . $item [$key] . '" selected="selected">' . $prefix . $item [$value] . '</option>';
			} else {
				echo '<option value="' . $item [$key] . '"  >' . $prefix . $item [$value] . '</option>';
			}
		
		}
	
	}
}

/*
 * ***************************
 * URL TITLE SANITIZER
 * ***************************
 */
function sanitizeSlug($name) {
	$name = ereg_replace ( "[^A-Za-z0-9-]", "", $name );
	while ( strpos ( $name, '--' ) ) {
		$name = str_replace ( '--', '-', $name );
	}
	return strtolower ( $name );
}

/*
 * ********************************
 * RANDOM PASSWORD GENERATOR
 * ********************************
 */
function createRandomPassword($count) {
	$chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-!?&{[}]~";
	$charcount = strlen ( $chars );
	
	srand ( ( double ) microtime () * 1000000 );
	$i = 0;
	$pass = '';
	while ( $i <= $count ) {
		$num = rand () % $charcount;
		//echo $num.'<br >';
		$tmp = substr ( $chars, $num, 1 );
		$pass = $pass . $tmp;
		$i ++;
	}
	return $pass;
}

/*
 * ***************************************
 * GET DATE AND TIME FROM GIVEN MICROTIME
 * ***************************************
 */
function getDateTime($micro) {
	if (! $micro) {
		$micro = microtime ();
	}
	
	list ( $microSec, $timeStamp ) = explode ( " ", micro );
	return date ( 'F jS, Y, H:i:', $timeStamp ) . (date ( 's', $timeStamp ));

}

/*
 * ***************************************
 * Checks whether admin is logged in
 * ***************************************
 */

function admin_logged_in() {
	if (! Session::newInstance ()->_get ( 'admin_id' )) {
		return false;
	}
	return true;
}

/*
 * *******************************
 * SANITIZES URI
 * *******************************
 */

function sanitizeURI($uri) {
	if ($uri == '') {
		throw new Exception ( 'Empty uri provided.' );
	}
	
	if (substr ( $uri, - 1 ) == '/') {
		$uri .= '/';
	}
	$uri = str_replace ( '//', '/', $uri ); // removes duplicate slashes
	

	// REMOVE DUPLICATE ?
	$uri = str_replace ( '??', '?', $uri );
	// REMOVE DUPLICATE &	
	$uri = str_replace ( '&&', '&', $uri );
	return str_replace ( 'http:/', 'http://', $uri );
}

/*
 * *******************************
 * SANITIZES FILE NAMES
 * *******************************
 */

function sanitize_file_name($filename) {
	$filename_raw = $filename;
	$special_chars = array ("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr ( 0 ) );
	$filename = str_replace ( $special_chars, '', $filename );
	$filename = preg_replace ( '/[\s-]+/', '-', $filename );
	$filename = trim ( $filename, '.-_' );
	return $filename;
}

/*
 * ***************************************************************
 * Validates duplicate slug entry in category and other places
 *  * ***************************************************************
 *  @return false if valid and true if invalid
 */

function checkSlug($slug) {
	if ($slug == '') {
		throw new Exception ( 'Empty Slug Provided' );
	}
	if (Model_Mapper_Categories::newInstance ()->getBySlug ( $slug )) {
		return true;
	}
	
	if (Model_Mapper_Locations::newInstance ()->getBySlug ( $slug )) {
		return true;
	}
	
	if (Model_Mapper_Items::newInstance ()->getBySlug ( $slug )) {
		return true;
	}
	return false;
}

function getMessage($name) {
	$msgs = Session::newInstance ()->_getMessage ( $name );
	if ($msgs ['msg']) {
		return $msgs ['msg'];
	} else {
		return false;
	}
}

/* 
 * ************************************************************
 * Date Time Differnce Function returns in array
 * ************************************************************
 */

function date_diff_array(DateTime $oDate1, DateTime $oDate2) {
	$aIntervals = array ('year' => 0, 'month' => 0, 'week' => 0, 'day' => 0, 'hour' => 0, 'minute' => 0, 'second' => 0 );
	
	foreach ( $aIntervals as $sInterval => &$iInterval ) {
		while ( $oDate1 <= $oDate2 ) {
			$oDate1->modify ( '+1 ' . $sInterval );
			if ($oDate1 > $oDate2) {
				$oDate1->modify ( '-1 ' . $sInterval );
				break;
			} else {
				$iInterval ++;
			}
		}
	}
	
	return $aIntervals;
}